import React from 'react';
import { Input, Form, Cascader, Radio, Modal, Button, message, Table, Switch } from 'antd';
import UploadImg from '../../../component/Upload/Upload';
import PopoverBtn from '../../../component/PopoverBtn/PopoverBtn';
import axios from '../../../utils/http';
import AddClass from '../AddClass/AddClass';
import { inject, observer } from 'mobx-react';

const { Column } = Table;
@inject('classMobx')
@observer
class ClassManageIndex extends React.Component {
  state = {
    classList: [],
    visible: false,
    currentItem: {},
    optionLists: [],
    cascaderAble: false,
  };
  showModal = () => {
    this.setState({
      visible: true,
    });
  };

  /* 修改分类 */
  handleOk = () => {
    let state = false;
    for (let k in this.state.currentItem) {
      if (this.state.currentItem[k] === '') {
        state = true;
      }
    }
    if (state) {
      console.log(this.state.currentItem);
      message.error('请填写所有表单项！');
    } else {
      console.log(this.state.currentItem);
      this.setState({
        visible: false,
      });
      this.classModify();
    }
  };

  /* 修改 */
  classModify = () => {
    let form = new FormData();
    for (let k in this.state.currentItem) {
      form.append(toHump(k), this.state.currentItem[k]);
    }
    axios({
      url: '/mm-goods/goods/updateGoodsClass',
      method: 'post',
      data: form,
    }).then(({ data }) => {
      if (data.code === 200) {
        message.success('分类更改成功！');
        this.getAllClass();
      }
    });
  };

  handleCancel = () => {
    this.setState({
      visible: false,
      currentItem: {},
    });
  };
  componentDidMount = () => {
    this.getAllClass();
    this.getOneClass();
  };

  /* 获取所有分类数据 */
  getAllClass = () => {
    axios({
      url: '/mm-goods/goods/queryGoodsClass',
      method: 'get',
    }).then(({ data }) => {
      this.setState({
        classList: [...data.data],
      });
    });
  };

  /* 更改商品分类排序 */
  updateSort = (val, id) => {
    axios({
      url: '/mm-goods/goods/updateGoodsC',
      method: 'get',
      params: {
        goodsCid: id,
        goodsCsort: val,
      },
    }).then(({ data }) => {
      if (data.code === 200) {
        message.success('排序修改成功');
        this.getAllClass();
      }
    });
  };

  /* 更改分类状态 */
  updateStus = (id, stus) => {
    axios({
      url: '/mm-goods/goods/updateGoodsClSt',
      method: 'get',
      params: {
        goodsCid: id,
        goodsCstatus: stus === true ? 1 : 0,
      },
    }).then(({ data }) => {
      if (data.code === 200) {
        message.success('状态修改成功');
        this.getAllClass();
      } else {
        message.error('状态修改失败');
      }
    });
  };

  /* 获取一级数据 */
  getOneClass = () => {
    axios({
      url: '/mm-goods/goods/queryGoodsCyi',
    }).then(({ data }) => {
      let arr = data.data.map(item => {
        return {
          value: item.goods_cid,
          label: item.goods_cname,
          isLeaf: true,
        };
      });
      this.setState({
        optionLists: arr,
      });
    });
  };

  /* 修改  数据回显 */
  modifyClass = item => {
    this.showModal();
    let target = Object.assign({}, this.state.currentItem, item);
    item.good_pid == 0
      ? this.setState({
          cascaderAble: true,
          currentItem: { ...target },
        })
      : this.setState({
          cascaderAble: false,
          currentItem: { ...target },
        });
  };

  /* 表单绑定 */
  formChange = (name, val) => {
    let obj = this.state.currentItem;
    obj[name] = val;
    this.setState({
      currentItem: obj,
    });
  };

  render() {
    return (
      <>
        <Modal
          title="添加分类"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          width="600px"
          className="addClass"
          destroyOnClose
        >
          <div className="addClassBox">
            <Form>
              {/* 分类名称 */}

              <Form.Item
                label="分类名称"
                name="分类名称"
                rules={[{ required: true, message: '请输入分类名称' }]}
                hasFeedback
              >
                <Input
                  defaultValue={this.state.currentItem.goods_cname}
                  value={this.state.currentItem.goods_cname}
                  onChange={e => this.formChange('goods_cname', e.target.value)}
                  placeholder="分类名称"
                />
              </Form.Item>

              {/* 分类logo */}
              <Form.Item
                label="分类logo"
                name="分类logo"
                rules={[{ required: true, message: '请上传分类图片' }]}
                hasFeedback
              >
                <UploadImg
                  maxNum={1}
                  Size={2}
                  formChange={this.formChange}
                  type="modify"
                  defaultValue={this.state.currentItem.goods_clogo}
                ></UploadImg>
              </Form.Item>
              {/* 上级分类 */}
              <Form.Item label="上级分类">
                <Cascader
                  className="classSelect"
                  bordered={false}
                  options={this.state.optionLists}
                  changeOnSelect
                  onChange={e => this.formChange('good_pid', e[e.length - 1])}
                  disabled={this.state.cascaderAble}
                  value={[this.state.currentItem.goods_cid]}
                />
                <p className="tip_p" style={{ paddingLeft: '20px' }}>
                  如不选择，该分类默认是一级分类
                </p>
              </Form.Item>
              {/* 数量单位 */}
              <Form.Item
                label="数量单位"
                name="数量单位"
                rules={[{ required: true, message: '请输入数量单位' }]}
              >
                <Input
                  value={this.state.currentItem.goods_cnu}
                  defaultValue={this.state.currentItem.goods_cnu}
                  onChange={e => this.formChange('goods_cnu', e.target.value)}
                  placeholder="数量单位，例千克，克等"
                />
              </Form.Item>
              {/* 分类排序 */}
              <Form.Item
                label="分类排序"
                name="分类排序"
                rules={[{ required: true, message: '请输入分类排序' }]}
              >
                <Input
                  type="number"
                  placeholder="数量单位，若不添默认为50"
                  value={this.state.currentItem.goods_csort}
                  defaultValue={this.state.currentItem.goods_csort}
                  onChange={e => this.formChange('goods_csort', e.target.value)}
                />
              </Form.Item>
              {/* 是否显示 */}
              <Form.Item label="是否显示" name="是否显示">
                <Radio.Group
                  defaultValue="1"
                  value={this.state.currentItem.goods_cstatus}
                  defaultValue={this.state.currentItem.goods_cstatus}
                  onChange={e => this.formChange('goods_cstatus', e.target.value)}
                >
                  <Radio value={1}>是</Radio>
                  <Radio value={0}>否</Radio>
                </Radio.Group>
              </Form.Item>
              {/* 关键字 */}
              <Form.Item
                label="关 键 字"
                name="关键字"
                rules={[{ required: true, message: '请输入关键字' }]}
              >
                <Input
                  value={this.state.currentItem.goods_kw}
                  defaultValue={this.state.currentItem.goods_kw}
                  onChange={e => this.formChange('goods_kw', e.target.value)}
                  placeholder="关键字，可优化搜索，非必填"
                />
              </Form.Item>
              {/* 分类描述 */}
              <Form.Item
                label="分类描述"
                name="分类描述"
                rules={[{ required: true, message: '分类描述' }]}
              >
                <Input.TextArea
                  value={this.state.currentItem.goods_cm}
                  defaultValue={this.state.currentItem.goods_cm}
                  onChange={e => this.formChange('goods_cm', e.target.value)}
                  placeholder="分类描述"
                />
              </Form.Item>
            </Form>
          </div>
        </Modal>

        <AddClass getAllClass={this.getAllClass} {...this.state}></AddClass>
        <p style={{ textAlign: 'center' }}>删除分类前，请先删除其下级所有分类</p>
        <Table
          dataSource={this.state.classList}
          pagination={{
            defaultPageSize: 5,
            total: this.state.classList.length,
            pageSizeOptions: [5, 10, 15],
            defaultCurrent: 1,
          }}
          rowKey="goods_cid"
        >
          <Column
            title="排序"
            key="goods_csort"
            width="100px"
            render={({ goods_csort, goods_cid }) => {
              return (
                <>
                  <Input
                    style={{ textAlign: 'center' }}
                    type="number"
                    defaultValue={goods_csort}
                    onBlur={e => {
                      this.updateSort(e.target.value, goods_cid);
                    }}
                  />
                </>
              );
            }}
            align="center"
          ></Column>
          <Column
            align="center"
            title="分类名称"
            dataIndex="goods_cname"
            key="goods_cname"
          ></Column>
          <Column
            title="是否显示"
            key="goods_cstatus"
            render={({ goods_cstatus, goods_cid }) => {
              return (
                <>
                  <Switch
                    defaultChecked={!!goods_cstatus}
                    onChange={e => this.updateStus(goods_cid, e)}
                  ></Switch>
                </>
              );
            }}
            align="center"
          ></Column>
          <Column
            title="操作"
            render={item => {
              return (
                <>
                  <Button type="link" onClick={() => this.modifyClass(item)}>
                    修改
                  </Button>
                  <PopoverBtn item={item} />
                </>
              );
            }}
            align="center"
          ></Column>
        </Table>
      </>
    );
  }
}
function toHump(name) {
  return name.replace(/\_(\w)/g, function (all, letter) {
    return letter.toUpperCase();
  });
}
export default ClassManageIndex;
